using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using CommonTypes;
using MVCFramework.Models.Filters;

namespace MVCFramework.Models
{
    public class FilterDecorator : ModelDecorator
    {
        private IFilter filter;
        public IFilter Filter
        {
            get { return filter; }
            set { filter = value; }
        }

        public FilterDecorator(IModel model, IFilter filter)
            : base(model)
        {
            this.filter = filter;
        }

        public override IEnumerator GetEnumerator()
        {
            if (Filter != null)
                if (Filter.IsActivated)
                {
                    foreach (object data in Model)
                        if (Filter.CheckGet(data))
                            yield return data;
                }
                else yield  return Model.GetEnumerator();
            else yield  return Model.GetEnumerator();
           
        }

        public override IList<IModelData> GetGroup(string name)
        {
            List<IModelData> filtered = new List<IModelData>();
            IList<IModelData> datalist = Model.GetGroup(name);

            if (Filter != null && Filter.IsActivated)
            {
                if (datalist != null)
                    foreach (IModelData dat in datalist)
                        if (Filter.CheckGet(dat))
                            filtered.Add(dat);
                return filtered;
            }
            else return base.GetGroup(name);
        }

        public override IList<IModelData> this[string name]
        {
            get
            {
                return GetGroup (name);
            }
        }

        public override bool AddObject(IModelData _object)
        {
            if (filter.IsActivated)
            {
                if (filter.CheckAdd(_object))
                    return base.AddObject(_object);
                else return false;
            }
            else return base.AddObject(_object);
        }
    }
}
